package com.qujia.station.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.GradeQrSetting;
import com.qujia.station.mapper.GradeQrSettingMapper;
import com.qujia.station.service.IGradeQrSettingService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @date 2024/1/16
 */
@Service
public class GradeQrSettingServiceImpl extends ServiceImpl<GradeQrSettingMapper, GradeQrSetting> implements IGradeQrSettingService {

    @Override
    public GradeQrSetting querySetting(String gradeCode) {
        SysUser loginSysUser = SecurityUtils.getLoginSysUser();
        Long enterpriseId = loginSysUser.getEnterpriseId();
        if (enterpriseId == null) {
            return null;
        }
        LambdaQueryWrapper<GradeQrSetting> qw = Wrappers.lambdaQuery(GradeQrSetting.class);
        qw.eq(GradeQrSetting::getEnterpriseId,enterpriseId)
                .eq(GradeQrSetting::getGradeCode,gradeCode)
                .last("limit 1");
        GradeQrSetting one = getOne(qw);
        if (one == null) {
            one = new GradeQrSetting();
            one.setGradeCode(gradeCode);
            one.setEnterpriseId(enterpriseId);
            one.setVersion(0L);
        }
        return one;
    }

    @Override
    public GradeQrSetting saveSetting(GradeQrSetting setting) {
        GradeQrSetting qrSetting = querySetting(setting.getGradeCode());
        SysUser sysUser = SecurityUtils.getLoginSysUser();
        setting.setEnterpriseId(sysUser.getEnterpriseId());
        if (qrSetting == null || qrSetting.getId() == null) {
            setting.setId(null);
            setting.setCreateBy(String.valueOf(sysUser.getUserId()));
            setting.setCreateTime(LocalDateTime.now());
            setting.setVersion(0L);
            save(setting);
        }else{
            setting.setId(qrSetting.getId());
            setting.setUpdateBy(String.valueOf(sysUser.getUserId()));
            setting.setUpdateTime(LocalDateTime.now());
            setting.setVersion(qrSetting.getVersion()+1);
            updateById(setting);
        }
        return setting;
    }
}
